package org.schat;

import java.net.Socket;
import java.util.Map.Entry;
import java.util.Set;

/**
 * @Description 客户端在线状态监测线程
 * @Author lsh
 **/
public class OnlineStatusRunnable implements Runnable{

	@Override
	public void run() {
		while(true){
			Set<Entry<String, ClientDomain>> clientSet=IMServer.clientMap.entrySet();
			for(Entry<String, ClientDomain> entry:clientSet){
				ClientDomain clientDomain=entry.getValue();
				Socket socket=clientDomain.getSocket();
				if(socket.isClosed()) {
					removeOfflineClient(clientDomain);
				}
				long time=System.currentTimeMillis()-clientDomain.getLastAcceptTime();
				if(time >= 2000){
					removeOfflineClient(clientDomain);
					if("-1".equals(clientDomain.getAuthorization())){
						System.out.print(clientDomain.getIp()+":"+clientDomain.getPort()+"未授权，即将关闭该连接！");
					}
				}
			}
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}

	//移除离线状态的客户端
	private void removeOfflineClient(ClientDomain clientDomain) {
        IMServer.removeClient(clientDomain);
		String msg=clientDomain.getClientName()+" 离开沙雕聊天室！";
		System.out.println(msg);
		IMServer.msgQue.offer(new MessageDomain("1",msg));
	}

}
